package com.oracle.lingshangejia.activity.special;

import android.app.DatePickerDialog;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.oracle.lingshangejia.Constant;
import com.oracle.lingshangejia.R;
import com.oracle.lingshangejia.adapter.special.ChanHou42ArchivesExtendableListAdapter;
import com.oracle.lingshangejia.bean.DataBean;
import com.oracle.lingshangejia.bean.User;
import com.oracle.lingshangejia.dialog.LoadingViewDialog;
import com.oracle.lingshangejia.model.OkgoNetwork;
import com.oracle.lingshangejia.utils.MyLogger;
import com.oracle.lingshangejia.utils.MyToast;
import com.oracle.lingshangejia.utils.ObserverOnNext;
import com.oracle.lingshangejia.utils.RxUtils;

import org.json.JSONObject;

import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

//孕产妇产后42天健康检查记录
public class ChanHou42MainActivity extends AppCompatActivity {
    private ExpandableListView expandableListView;
    private ChanHou42ArchivesExtendableListAdapter archivesExtendableListAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ch42_add_archives_activity);
        initBasic();
        expandableListView = findViewById(R.id.expend_list);
        expandableListView.setGroupIndicator(null);
        String[] archivesStr = getResources().getStringArray(R.array.chan_hou_42_archives);
        archivesExtendableListAdapter = new ChanHou42ArchivesExtendableListAdapter(archivesStr);
        expandableListView.setAdapter(archivesExtendableListAdapter);
        // 添加末尾提交按钮
        View foot = LayoutInflater.from(this).inflate(R.layout.archives_foot_submit, null);
        expandableListView.addFooterView(foot);

        expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return false;
            }
        });

        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                int count = expandableListView.getExpandableListAdapter().getGroupCount();
                for (int i = 0; i < count; i++) {
                    if (i != groupPosition) {
                        expandableListView.collapseGroup(i);
                    }
                }
            }
        });
        expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
            @Override
            public void onGroupCollapse(int groupPosition) {
                View[] views = ((ChanHou42ArchivesExtendableListAdapter) expandableListView.getExpandableListAdapter()).getConvertViews();
                View view = views[groupPosition];
                if (view == null) {
                    return;
                }
                Map<String, String> values = null;
                switch (groupPosition) {
                    case 0:
                        values = getBasicInfoValues();
                        break;
                    case 1:
                        values = getEducationAndProfessionalAndMarriageAndPayValues(view);
                        break;
                    case 2:
                        values = getAllergyAndExposedValues(view);
                        break;
                    case 3:
                        values = getDiseaseValues(view);
                        break;
                }

            }
        });

        expandableListView.expandGroup(0);

    }


    /**
     * 检查用户名、身份证号和本人联系电话是否正确填写
     *
     * @return 数据不正确返回true，正确返回false
     */
    private boolean checkBasicInfoIsError() {
        Map<String, String> basicInforValues = getBasicInfoValues();
        String xm = (String) basicInforValues.get("xm");

        // 姓名非空验证
        if (xm == null || xm.length() == 0) {
            Toast.makeText(getApplicationContext(), "姓名必须填写", Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }




    private Calendar calendar;
    private DatePickerDialog dialog;
    /*时间*/
    public void onTimeViewClick(final View v) {
        calendar = Calendar.getInstance();
        dialog = new DatePickerDialog(ChanHou42MainActivity.this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year,
                                          int monthOfYear, int dayOfMonth) {
                        TextView tv = (TextView) v;
                        String month;
                        String day;
                        if (monthOfYear <9){
                            month = "0"+(monthOfYear+1);
                        }else {
                            month = ""+(monthOfYear+1);
                        }
                        if (dayOfMonth <10){
                            day = "0"+dayOfMonth;
                        }else {
                            day = dayOfMonth + "";
                        }
                        tv.setText(year + "-" + month  + "-" + day);

                    }
                }, calendar.get(Calendar.YEAR), calendar
                .get(Calendar.MONTH), calendar
                .get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

    /**
     * "乳房"按钮点击事件处理
     */
    public void changeBreastEnableEdit(View view) {
        EditText ed = findViewById(R.id.a_postpartum_housecall_breast_abnormalities_text);
        RadioButton rb = (RadioButton) view;
        if (view.getId() == R.id.a_postpartum_housecall_breast_no_abnormalities) {
            ed.setText("");
            ed.setEnabled(false);
        } else if (rb.isChecked()) {
            ed.setEnabled(true);
            ed.setFocusable(true);
            ed.setFocusableInTouchMode(true);
            ed.requestFocus();
        }
    }
    /**
     * "恶露"按钮点击事件处理
     */
    public void changeLochiaEnableEdit(View view) {
        EditText ed = findViewById(R.id.a_postpartum_housecall_lochia_abnormalities_text);
        RadioButton rb = (RadioButton) view;
        if (view.getId() == R.id.a_postpartum_housecall_lochia_no_abnormalities) {
            ed.setText("");
            ed.setEnabled(false);
        } else if (rb.isChecked()) {
            ed.setEnabled(true);
            ed.setFocusable(true);
            ed.setFocusableInTouchMode(true);
            ed.requestFocus();
        }
    }
    /**
     * "子宫"按钮点击事件处理
     */
    public void changeUterusEnableEdit(View view) {
        EditText ed = findViewById(R.id.a_postpartum_housecall_uterus_abnormalities_text);
        RadioButton rb = (RadioButton) view;
        if (view.getId() == R.id.a_postpartum_housecall_uterus_no_abnormalities) {
            ed.setText("");
            ed.setEnabled(false);
        } else if (rb.isChecked()) {
            ed.setEnabled(true);
            ed.setFocusable(true);
            ed.setFocusableInTouchMode(true);
            ed.requestFocus();
        }
    }
    /**
     * "伤口"按钮点击事件处理
     */
    public void changeWoundEnableEdit(View view) {
        EditText ed = findViewById(R.id.a_postpartum_housecall_wound_abnormalities_text);
        RadioButton rb = (RadioButton) view;
        if (view.getId() == R.id.a_postpartum_housecall_wound_no_abnormalities) {
            ed.setText("");
            ed.setEnabled(false);
        } else if (rb.isChecked()) {
            ed.setEnabled(true);
            ed.setFocusable(true);
            ed.setFocusableInTouchMode(true);
            ed.requestFocus();
        }
    }
    //分类
    public void onGuidanceClick(View view) {
        EditText ed1 = findViewById(R.id.a_postpartum_housecall_guidance_5_text);
        RadioButton rb = (RadioButton) view;
        if (view.getId() == R.id.a_postpartum_housecall_guidance_5) {
            ed1.setEnabled(true);
        } else{
            ed1.setText("");
            ed1.setEnabled(false);
        }

    }
    /*转诊*/
    public void onReferralClick(View view) {
        EditText ed1 = findViewById(R.id.a_postpartum_housecall_referra_yes_reason);
        EditText ed2 = findViewById(R.id.a_postpartum_housecall_referra_yes_mechanism);
        EditText ed3 = findViewById(R.id.a_postpartum_housecall_referra_yes_mechanis);
        RadioButton rb = (RadioButton) view;
        if (view.getId() == R.id.a_postpartum_housecall_referra_no) {
            ed1.setText("");
            ed1.setEnabled(false);
            ed2.setText("");
            ed2.setEnabled(false);
            ed3.setText("");
            ed3.setEnabled(false);
        } else if (rb.isChecked()) {
            ed1.setEnabled(true);
            ed2.setEnabled(true);
            ed3.setEnabled(true);
        }
    }

    /**
     * 获取基本信息数据
     */
    private Map<String, String> getBasicInfoValues() {
        View[] views = ((ChanHou42ArchivesExtendableListAdapter) expandableListView.getExpandableListAdapter()).getConvertViews();
        View view = views[0];
        Map<String, String> params = new HashMap<>();
        // 姓名
        String username = "";
        //随访日期
        String dateofdelivery = "";
        //分娩日期
        String chiefcomplaint = "";
        //出院日期
        String dischargedate= "";
        // 一般健康情况
        String health = "";
        //一般心理状况
        String sychologicalstapte = "";
        //血压收缩率
        String bloodpressure = "";
        //血压舒张绿
        String bloodpressur = "";
        //居民id
        String esurid = "";
        //医生id
        String doctorid = "";
        //丈夫姓名
        String husbandname = "";
        //丈夫年龄
        String husbandold = "";
        //丈夫电话
        String husbandnumber = "";

       // username = ((EditText) view.findViewById(R.id.a_postpartum_housecall_username)).getText().toString().trim();
       // dateofdelivery = ((TextView) view.findViewById(R.id.a_postpartum_housecall_follow_up_date)).getText().toString().trim();
        chiefcomplaint = ((TextView) view.findViewById(R.id.a_postpartum_housecall_date_of_delivery)).getText().toString().trim();
        dischargedate= ((TextView) view.findViewById(R.id.a_postpartum_housecall_discharge_date)).getText().toString().trim();
        health = ((EditText) view.findViewById(R.id.a_postpartum_housecall_general_health_status)).getText().toString().trim();
        sychologicalstapte = ((EditText) view.findViewById(R.id.a_postpartum_housecall_general_psychological_status)).getText().toString().trim();
        bloodpressure  = ((EditText) view.findViewById(R.id.a_postpartum_housecall_blood_pressure)).getText().toString().trim();
        bloodpressur  = ((EditText) view.findViewById(R.id.a_postpartum_housecall_blood_pressur)).getText().toString().trim();
       // esurid  = ((EditText) view.findViewById(R.id.a_postpartum_housecall_userid)).getText().toString().trim();
      //  doctorid  = ((EditText) view.findViewById(R.id.a_postpartum_housecall_doctorid)).getText().toString().trim();
     //   husbandname  = ((EditText) view.findViewById(R.id.a_postpartum_housecall_husbandname)).getText().toString().trim();
     //   husbandnumber  = ((EditText) view.findViewById(R.id.a_postpartum_housecall_husbandnumber)).getText().toString().trim();
     //   husbandold  = ((EditText) view.findViewById(R.id.a_postpartum_housecall_husbandold)).getText().toString().trim();
      //  params.put("xm", username);
      //  params.put("sfrq", dateofdelivery);
        params.put("fwrq", chiefcomplaint);//分娩
        params.put("cyrq", dischargedate);//出院
        params.put("ybjkzk", health);//健康
        params.put("ybxlzk", sychologicalstapte);//心理
        params.put("xySsl", bloodpressure );//
        params.put("xySzl", bloodpressur );//
       // params.put("grjbxx_id", esurid );
       // params.put("create_by", doctorid );
      /*  params.put("zfxm", husbandname );
        params.put("zfnl", husbandold );
        params.put("zfdh", husbandnumber );*/
         mValues.putAll(params);
        return params;
    }

    /**
     * 第二页
     */
    private Map<String, String> getEducationAndProfessionalAndMarriageAndPayValues(View view) {
        Map<String, String> params = new HashMap<>();
        // 乳房
        String breast = "";
        //乳房异常描述
        String breastText="";
        //恶露
        String ochia = "";
        //恶露异常描述
        String ochiaText="";
        //子宫
        String uterus = "";
        //子宫异常描述
        String uterusText="";
        //伤口
        String Wound = "";
        //伤口异常描述
        String WoundText="";
        //其他
        String other = "";

        if (view != null) {
            RadioButton none = view.findViewById(R.id.a_postpartum_housecall_breast_no_abnormalities);
            RadioButton all = view.findViewById(R.id.a_postpartum_housecall_breast_abnormalities);
            if (none.isChecked()) {
                String s = none.getText().toString().trim();
                s = s.substring(0, s.indexOf(" "));
                breast  = s;
            } else {
                String s = all.getText().toString().trim();
                if (s.length() > 0)
                    s = s.substring(0, s.indexOf(" "));
                breast  = s;
            }
            breastText = ((EditText) view .findViewById(R.id.a_postpartum_housecall_breast_abnormalities_text)).getText().toString().trim();
        }

        if (view != null) {
            RadioButton none = view.findViewById(R.id.a_postpartum_housecall_lochia_no_abnormalities);
            RadioButton all = view.findViewById(R.id.a_postpartum_housecall_lochia_abnormalities);
            if (none.isChecked()) {
                String s = none.getText().toString().trim();
                s = s.substring(0, s.indexOf(" "));
                ochia  = s;
            } else {
                String s = all.getText().toString().trim();
                if (s.length() > 0)
                    s = s.substring(0, s.indexOf(" "));
                ochia  = s;
            }
            ochiaText = ((EditText) view .findViewById(R.id.a_postpartum_housecall_lochia_abnormalities_text)).getText().toString().trim();
        }



        if (view != null) {
            RadioButton none = view.findViewById(R.id.a_postpartum_housecall_uterus_no_abnormalities);
            RadioButton all = view.findViewById(R.id.a_postpartum_housecall_uterus_abnormalities);
            if (none.isChecked()) {
                String s = none.getText().toString().trim();
                s = s.substring(0, s.indexOf(" "));
                uterus  = s;
            } else {
                String s = all.getText().toString().trim();
                if (s.length() > 0)
                    s = s.substring(0, s.indexOf(" "));
                uterus  = s;
            }
            uterusText = ((EditText) view .findViewById(R.id.a_postpartum_housecall_uterus_abnormalities_text)).getText().toString().trim();
        }

        if (view != null) {
            RadioButton none = view.findViewById(R.id.a_postpartum_housecall_wound_no_abnormalities);
            RadioButton all = view.findViewById(R.id.a_postpartum_housecall_wound_abnormalities);
            if (none.isChecked()) {
                String s = none.getText().toString().trim();
                s = s.substring(0, s.indexOf(" "));
                Wound = s;
            } else {
                String s = all.getText().toString().trim();
                if (s.length() > 0)
                    s = s.substring(0, s.indexOf(" "));
                Wound = s;
            }
            WoundText = ((EditText) view .findViewById(R.id.a_postpartum_housecall_wound_abnormalities_text)).getText().toString().trim();
        }

        other = ((TextView) view.findViewById(R.id.a_postpartum_housecall_other)).getText().toString().trim();
        params.put("chRf", breast);//
        params.put("chRfYc", breastText);//
        params.put("chEl", ochia);//
        params.put("chElYc", ochiaText);//
        params.put("chZg", uterus);///
        params.put("chZgYc", uterusText);//
        params.put("chSk", Wound);//
        params.put("chSkYc", WoundText);//
        params.put("chQt", other);//
        mValues.putAll(params);

        return params;
    }

    /**
     * 第三页
     */
    private Map<String, String> getAllergyAndExposedValues(View view) {
        Map<String, String> params = new HashMap<>();
        //分类
        String classification = "";
        if (((RadioButton) view.findViewById(R.id.a_postpartum_housecall_classification_no_abnormalities)).isChecked()) {
            //national = "1 汉族";
            classification = "1";
        } else {
            //national = ((EditText) views[0].findViewById(R.id.archives_national_other)).getText().toString().trim();
            classification = "99";
        }
        params.put("chFl", classification);
        //指导
        String abnormal = "";
        // 指导其他
        String noabnormal = "";
        View[] payViews = getViews(view.findViewById(R.id.a_postpartum_housecall_guidance_1));
        for (int i = 0; i < payViews.length; i++) {
            if (payViews[i] instanceof CheckBox) {
                CheckBox cb = (CheckBox) payViews[i];
                if (cb.isChecked()) {
                    String s = cb.getText().toString().trim();
                    s = s.substring(0, s.indexOf(" "));
                    abnormal += s;
                    abnormal+= ",";
                }
            }
        }
        if (abnormal.length() != 0) {
            abnormal = abnormal.substring(0, abnormal.length() - 1);
        }
        noabnormal = ((EditText) view.findViewById(R.id.a_postpartum_housecall_guidance_5_text)).getText().toString().trim();

        params.put("zd", abnormal);
        params.put("zdQt", noabnormal);
        mValues.putAll(params);
        return params;
    }

    /**
     * 第四页
     */
    private Map<String, String> getDiseaseValues(View view) {
        Map<String, String> params = new HashMap<>();
        //转诊
        String zhuanzhen= "";
        //转诊
        String Reason = "";
        //转诊
        String jigou = "";
        //转诊
        String Room = "";

        if (((RadioButton) view.findViewById(R.id.a_postpartum_housecall_referra_no)).isChecked()) {
            zhuanzhen = "1";
        } else {
            zhuanzhen = "2";
            Reason = ((EditText) view.findViewById(R.id.a_postpartum_housecall_referra_yes_reason)).getText().toString().trim();
            jigou = ((EditText) view.findViewById(R.id.a_postpartum_housecall_referra_yes_mechanism)).getText().toString().trim();
            Room = ((EditText) view.findViewById(R.id.a_postpartum_housecall_referra_yes_mechanis)).getText().toString().trim();
        }
        params.put("cl", zhuanzhen);
        params.put("zzyy", Reason);
        params.put("zzjg", jigou);
        params.put("zzks", Room);



        //随访医生签字
        String gestationalage = "";

      // 下次随访日期
        String followupdate = "";
        gestationalage = ((EditText) view.findViewById(R.id.a_postpartum_housecall_doctor_signature)).getText().toString().trim();
        followupdate = ((TextView) view.findViewById(R.id.a_postpartum_housecall_next_follow_up_date)).getText().toString().trim();
        params.put("sfysqm", gestationalage);
        params.put("scsfsj", followupdate);//随访时间
        mValues.putAll(params);
        return params;
    }
    /**
     * Toolbar的事件---返回
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 获取子视图
     */
    private View[] views;

    private View[] getViews(View view) {
        views = new View[0];
        parseView(view);
        return views;
    }

    private void parseView(View view) {
        if (view instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) view;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View v = vg.getChildAt(i);
                parseView(v);
            }
        } else {
            views = Arrays.copyOf(views, views.length + 1);
            views[views.length - 1] = view;
        }
    }

    /**
     * 提交数据
     */
    public void onClickSubmit(View view) {
        showLoading();
        int count = expandableListView.getExpandableListAdapter().getGroupCount();
        for (int i = 0; i < count; i++) {
            expandableListView.collapseGroup(i);
        }
        Observable.create(new ObservableOnSubscribe<DataBean>() {
            @Override
            public void subscribe(ObservableEmitter<DataBean> emitter) throws Exception {
                JSONObject jsonObject = new JSONObject(mValues);
                MyLogger.i(jsonObject.toString());
                String json = OkgoNetwork.post(url,jsonObject.toString());
                MyLogger.i(json);
                Gson gson = new Gson();
                emitter.onNext(gson.fromJson(json, DataBean.class));

            }
        }).compose(RxUtils.io_main()).subscribe(new ObserverOnNext<DataBean>() {
            @Override
            public void onNext(DataBean dataBean) {
                if (dataBean.getCode()==0){
                    MyToast.show("提交成功");
                    finish();
                }else {
                    MyToast.show(dataBean.getMsg());
                }
                dismissLoading();

            }
        });

    }


    //新
    private Map<Object,Object> mValues = new HashMap<>();
    private  String url = Constant.baseurl+"online/zxdaycf/saveChset";
    private LoadingViewDialog mLoadingView;
    //整合专项  基础 修改
    private void initBasic(){
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        Toolbar toolbar = (Toolbar)findViewById(com.oracle.children.R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mValues.put("token", User.getToken());
        mValues.put("jmId",getIntent().getIntExtra("jmid", 0) );
        mValues.put("userId", User.getUserId());//社区医生id;
        mValues.put("mark", 1);
        //随访id
        int id = getIntent().getIntExtra("id", 0);
        if (id !=0){
            mValues.put("id", id);
            mValues.put("sfjlId", id);
        }
    }




    public void showLoading(){
        mLoadingView = new LoadingViewDialog();
        mLoadingView.show(getSupportFragmentManager(),"" );
    }
    public void dismissLoading(){
        if (mLoadingView != null){
            mLoadingView.dismiss();
        }

    }




}
